<template>
  <!-- <image src="@/static/login_bg.png" class="image-box"></image> -->
  <view class="login_page">
    <view class="header">
      <view class="title-box">
        <view class="title">登录</view>
        <view class="text"> 您好, 欢迎来到天玩 </view>
      </view>
    </view>
    <view class="main">
      <view class="login-box">
        <view class="form" v-if="loginType === 'phone'">
          <uv-form labelPosition="top" :model="form" ref="formRef">
            <uv-form-item prop="phone">
              <view class="ipt-box">
                <uv-input
                  type="number"
                  placeholder="请输入手机号"
                  border="none"
                  v-model="form.phone"
                  clearable
                  maxlength="11"
                  placeholder-class="placeholderStyle"
                ></uv-input>
              </view>
            </uv-form-item>
            <uv-form-item prop="code" v-if="accountLoginType === 'code'">
              <view class="ipt-box">
                <uv-input
                  type="number"
                  placeholder="请输入验证码"
                  placeholder-class="placeholderStyle"
                  border="none"
                  v-model="form.code"
                  :maxlength="6"
                >
                  <template v-slot:suffix>
                    <uv-code
                      ref="uCodeRef1"
                      @change="codeChange1"
                      seconds="60"
                    ></uv-code>
                    <view
                      @click="getCode(1)"
                      style="color: #6e68e9; font-size: 28rpx"
                      >{{ codeTips }}</view
                    >
                  </template>
                </uv-input>
              </view>
            </uv-form-item>
            <uv-form-item prop="pwd" v-else>
              <view class="ipt-box">
                <uv-input
                  placeholder="请输入密码"
                  placeholder-class="placeholderStyle"
                  border="none"
                  v-model="form.pwd"
                  clearable
                  password
                ></uv-input>
              </view>
            </uv-form-item>
            <view class="check-box">
              <uv-checkbox-group
                style="flex: 0"
                shape="circle"
                v-model="form.checked"
                size="20"
                activeColor="#6F69E9"
              >
                <view style="display: flex; align-items: center">
                  <uv-checkbox name="true"></uv-checkbox>
                  <view style="font-size: 24rpx; color: #666666">
                    我已阅读并同意<text
                      style="color: #453de7"
                      @click="handleClick(7)"
                      >《服务协议》</text
                    >和<text style="color: #453de7" @click="handleClick(8)"
                      >《隐私政策》</text
                    >
                  </view>
                </view>
              </uv-checkbox-group>
            </view>
            <uv-button
              type="primary"
              text="登录"
              :disabled="!form.phone"
              @click="accountLogin"
              customTextStyle="font-size: 28rpx;color:#fff"
              customStyle="margin-top:132rpx;width:600rpx;border-radius: 40rpx;height: 80rpx;"
            ></uv-button>
            <uv-button
              v-if="accountLoginType === 'code'"
              type="info"
              text="手机号密码登录"
              plain
              :hairline="true"
              customTextStyle="font-size: 28rpx;color:#222222"
              @click="accountLoginChange('pwd')"
              customStyle="margin-top: 32rpx;width:600rpx;border-radius: 40rpx;height: 80rpx;border"
            ></uv-button>
            <uv-button
              v-if="accountLoginType === 'pwd'"
              type="info"
              text="手机号验证码登录"
              plain
              :hairline="true"
              customTextStyle="font-size: 28rpx;color:#222222"
              @click="accountLoginChange('code')"
              customStyle="margin-top: 32rpx;width:600rpx;border-radius: 40rpx;height: 80rpx;"
            ></uv-button>
          </uv-form>
        </view>
        <view class="bottom-box">
          <view
            class="bottom-text"
            @click="navigateTo('/pages/login/register')"
          >
            立即注册
          </view>
          <view class="high_line"></view>
          <view class="bottom-text" @click="switchTab('/pages/home/index')">
            进入首页
          </view>
          <view class="high_line" v-if="accountLoginType === 'pwd'"></view>
          <view
            class="bottom-text"
            v-if="accountLoginType === 'pwd'"
            @click="navigateTo('/pages/login/forget_pwd')"
          >
            忘记密码
          </view>
        </view>
        <!-- #ifndef H5 -->
        <view class="other-box">
          <uv-divider text="其他登录方式"></uv-divider>
          <view class="other-box-item">
            <image
              src="@/static/login/phone.png"
              mode="aspectFit"
              class="img"
              @click="loginChange('oauth')"
            />

            <!-- #ifdef MP-WEIXIN -->
            <button
              open-type="getPhoneNumber"
              @getphonenumber="getPhoneNumber"
              class="getPhoneBtn"
            ></button>
            <!-- #endif -->

            <!-- #ifdef APP-PLUS -->

            <image
              src="@/static/login/wechat.png"
              mode="aspectFit"
              class="img"
              @click="loginChange('wechat')"
            />
            <!-- #endif -->
          </view>
        </view>
        <!-- #endif -->
      </view>
    </view>
    <xzy-popup
      ref="popupRef"
      title="绑定手机号"
      btnText="提交"
      mode="center"
      :isShowClose="false"
      :isShowFooter="true"
      @submit="submit"
    >
      <view style="margin: 50rpx 0 30rpx">
        <view class="ipt-box">
          <uv-input
            type="number"
            placeholder="请输入手机号"
            prefixIcon="phone"
            border="none"
            :maxlength="11"
            v-model="bindPhoneForm.phone"
            clearable
          ></uv-input>
        </view>
        <view class="ipt-box" style="margin-top: 40rpx">
          <uv-input
            type="number"
            placeholder="请输入验证码"
            border="none"
            v-model="bindPhoneForm.smsCode"
            prefixIcon="chat"
            :maxlength="6"
          >
            <template v-slot:suffix>
              <uv-code
                ref="uCodeRef2"
                @change="codeChange2"
                seconds="60"
              ></uv-code>
              <view @click="getCode(2)">{{ bindPhoneText }}</view>
            </template>
          </uv-input>
        </view>
      </view>
    </xzy-popup>
  </view>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { checkStr, getOaidAndImei } from "@/utils";
import {
  GetWechatPhone,
  Login,
  SendSmsCode,
  UpdateCancelState,
  AppWechatLogin,
  WechatLogin,
  GetUserRuleList,
  RemovePushId,
} from "@/api/modules/system";
import Md5 from "js-md5";
import config from "@/api/config";

import useStore from "@/stores";
// #ifdef APP-PLUS
import { checkVerifyEnable, preLogin } from "@/utils/oauth";
const jpushModule = uni.requireNativePlugin("JG-JPush");
// #endif

const { globalStore } = useStore();

const form = reactive({
  phone: uni.getStorageSync("__DEFAULT_LOGIN_PHONE") ?? "",
  pwd: "",
  code: "",
  checked: [],
});
//	一键登录异常提示
const oneKeyTip = ref("");
onLoad((options) => {
  // #ifdef APP-PLUS
  // 	消息推送保存RegisterID
  jpushModule.getRegistrationID((result) => {
    globalStore.setRegisterID(result.registerID);
  });
  // #endif
  oneKeyTip.value = options.str;
  if (options.str) {
    uni.$uv.toast(options.str);
  }
});

const loginType = ref("phone");
const popupRef = ref();
const wechatRes = ref({});
//	登录方式切换 oauth: 一键登录; phone: 手机号登录; wechat: 微信登录
function loginChange(type) {
  if (type === "wechat") {
    // #ifdef APP-PLUS
    if (form.checked.length <= 0) {
      uni
        .$showModal({
          title: "",
          opacity: 0.8,
          content: "点击确定即代表您已阅读并同意《服务协议》和《隐私政策》",
          confirmVal: "确定",
          cancelVal: "取消",
        })
        .then(() => {
          form.checked.push("true");
          wechatLogin();
        });
    } else {
      wechatLogin();
    }
    // #endif
  } else if (type === "oauth") {
    if (oneKeyTip.value) {
      uni.$uv.toast(oneKeyTip.value);
      return;
    }

    // #ifdef APP-PLUS
    checkVerifyEnable().then((res) => {
      if (res) {
        preLogin().then((result) => {
          globalStore.login(result);
        });
      } else {
        uni.$uv.toast("移动数据不可用，请使用账号密码登录");
      }
    });
    // #endif
  }
}
//	微信小程序登录
function getPhoneNumber(e) {
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    WechatLogin({
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      code: e.detail.code,
    }).then((res) => {
      globalStore.login(res.data);
    });
  }
}

function wechatLogin() {
  uni.login({
    provider: "weixin",
    onlyAuthorize: true,
    success: async function (event) {
      const { code } = event;
      const { data } = await GetWechatPhone({
        code,
        registrationId: globalStore.registerID,
      });

      if (data?.tag * 1 === 0) {
        bindPhoneForm.phone = "";
        bindPhoneForm.smsCode = "";
        popupRef.value.open();
        wechatRes.value = data?.wxLoginUserResp;
      } else {
        globalStore.login(data.loginTokenResp);
      }
    },
    fail: function (err) {
      if (err.code === -8) {
        uni.$uv.toast("请安装微信客户端！");
      } else {
        uni.$uv.toast(err.errMsg);
      }
    },
  });
}

//	绑定手机号参数
const bindPhoneForm = reactive({
  phone: "",
  smsCode: "",
});
//	微信登陆绑定手机号提交
async function submit() {
  if (!bindPhoneForm.phone || !checkStr(bindPhoneForm.phone, "mobile")) {
    uni.$uv.toast("请输入正确的手机号");
    return;
  }
  if (!bindPhoneForm.smsCode || bindPhoneForm.smsCode.length !== 6) {
    uni.$uv.toast("请输入6位短信验证码");
    return;
  }

  const deviceInfo = await getOaidAndImei();
  AppWechatLogin({
    userSource: config.USER_SOURCE,
    ...wechatRes.value,
    ...bindPhoneForm,
    registrationId: globalStore.registerID,
    deviceType: deviceInfo.type,
    deviceId: deviceInfo.id,
  }).then((res) => {
    globalStore.login(res.data.loginTokenResp);
  });
}

const accountLoginType = ref("code");
//	账号登陆方式切换  code: 账号 + 短信验证码登录; pwd: 账号 + 密码登录
function accountLoginChange(type) {
  accountLoginType.value = type;
}
const formRef = ref();

const codeTips = ref("");
const bindPhoneText = ref("");
//	倒计时
function codeChange1(text) {
  codeTips.value = text;
}

function codeChange2(text) {
  bindPhoneText.value = text;
}

// 	获取验证码
const uCodeRef1 = ref();
const uCodeRef2 = ref();

function getCode(type) {
  if (
    type === 1
      ? !form.phone || !checkStr(form.phone, "mobile")
      : !bindPhoneForm.phone || !checkStr(bindPhoneForm.phone, "mobile")
  ) {
    uni.$uv.toast("请输入正确的手机号");
    return;
  }

  if (type === 1 && uCodeRef1.value.canGetCode) {
    // 模拟向后端请求验证码
    uni.showLoading({
      title: "正在获取验证码",
    });
    SendSmsCode({
      phone: type === 1 ? form.phone : bindPhoneForm.phone,
      isRegister: type === 1 ? 1 : 0,
    }).then((res) => {
      uni.hideLoading();
      uni.$uv.toast("验证码已发送");
      uCodeRef1.value.start();
    });
  } else {
    uni.$uv.toast("倒计时结束后再发送");
  }

  if (type === 2 && uCodeRef2.value.canGetCode) {
    // 模拟向后端请求验证码
    uni.showLoading({
      title: "正在获取验证码",
    });
    SendSmsCode({
      phone: type === 1 ? form.phone : bindPhoneForm.phone,
      isRegister: type === 1 ? 1 : 0,
    }).then((res) => {
      uni.hideLoading();
      uni.$uv.toast("验证码已发送");
      uCodeRef2.value.start();
    });
  } else {
    uni.$uv.toast("倒计时结束后再发送");
  }
}

function accountLogin() {
  if (accountLoginType.value === "code") {
    if (!form.phone || !checkStr(form.phone, "mobile")) {
      uni.$uv.toast("请输入正确的手机号");
      return;
    }
    if (!form.code || form.code.length !== 6) {
      uni.$uv.toast("请输入6位短信验证码");
      return;
    }
  } else {
    if (!form.phone || !checkStr(form.phone, "mobile")) {
      uni.$uv.toast("请输入正确的手机号");
      return;
    }
    // if (!form.pwd || !checkStr(form.pwd, 'mixed')) {
    // 	uni.$uv.toast('请输入至少6位数字、字母或数字 + 字母组合(不区分大小写)')
    // 	return
    // }
  }
  if (form.checked.length <= 0) {
    uni
      .$showModal({
        title: "",
        opacity: 0.8,
        content: "点击确定即代表您已阅读并同意《服务协议》和《隐私政策》",
        confirmVal: "确定",
        cancelVal: "取消",
      })
      .then(() => {
        form.checked.push("true");
        handleLogin();
      });
  } else {
    handleLogin();
  }
}

async function handleLogin() {
  const MD5_PWD = Md5(form.pwd);
  const deviceInfo = await getOaidAndImei();
  const data =
    accountLoginType.value === "code"
      ? {
          deviceType: deviceInfo.type,
          deviceId: deviceInfo.id,
          phone: form.phone,
          smsCode: form.code,
          userSource: config.USER_SOURCE,
          registrationId: globalStore.registerID,
          tag: 2,
        }
      : {
          deviceType: deviceInfo.type,
          deviceId: deviceInfo.id,
          phone: form.phone,
          loginPwd: MD5_PWD,
          registrationId: globalStore.registerID,
          tag: 1,
        };
  Login(data).then((res) => {
    if (res.data.userInfo?.isDelete * 1 === 1) {
      uni
        .$showModal({
          title: "",
          content: "该账号已注销，是否确定恢复！",
          confirmVal: "确定",
          cancelVal: "取消",
        })
        .then(() => {
          globalStore.login(res.data, "update");
        });
    } else {
      globalStore.login(res.data);
    }
  });
}
const ruleData = ref({});
const ruleModalRef = ref();
const handleClick = (code) => {
  uni.navigateTo({
    url: `/pages/system/privacy_agreement?code=${code}`,
  });
};

function navigateTo(url) {
  uni.navigateTo({
    url,
  });
}

function switchTab(url) {
  uni.switchTab({
    url,
  });
}
</script>
<style scoped lang="scss">
:deep(.uv-checkbox-group) {
  flex: 0 !important;
}

.login_page {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background-size: contain;
  background-image: url("https://static.tianwandailian.cn/static/server/newimage/order_bg.png");
  background-repeat: no-repeat;

  .header {
    height: 352rpx;
    width: 100%;
    position: relative;

    .title-box {
      margin: 206rpx 76rpx 0;

      .title {
        color: #222;
        font-size: 64rpx;
        font-weight: 600;
      }

      .text {
        color: #666666;
        font-size: 40rpx;
        margin-top: 16rpx;
      }
    }

    .tip {
      font-size: 24rpx;
      color: #888888;
      margin-top: 30rpx;
      margin-left: 76rpx;
    }

    .goback {
      position: absolute;
      left: 40rpx;
      top: 100rpx;
      cursor: pointer;
      width: 60rpx;
      height: 60rpx;
    }
  }

  .main {
    width: calc(100vw - 152rpx);
    padding: 0 76rpx;
    flex: 1;
    display: flex;

    .login-box {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      /* #ifndef H5 */
      justify-content: space-around;
      /* #endif */

      .oauth {
        text-align: center;
        margin-top: 242rpx;

        .number {
          font-size: 60rpx;
          font-weight: 700;
          color: #222;
        }

        .tip {
          margin-top: 30rpx;
          font-size: 28rpx;
          color: #888;
        }

        .btn-box {
          margin-top: 120rpx;
        }
      }

      .form {
        margin-top: 100rpx;
        /* #ifdef APP-PLUS */
        margin-bottom: 20rpx;
        /* #endif */
        /* #ifndef APP-PLUS */
        margin-bottom: 100rpx;
        /* #endif */

        .uv-form {
          width: 100%;
        }
      }

      .login-rule {
        margin-top: 20rpx;
      }

      .other-box {
        width: 100%;
        margin-bottom: 140rpx;
        text-align: center;

        .other-box-item {
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;

          .getPhoneBtn {
            position: absolute;
            width: 100rpx;
            height: 100rpx;
            background: transparent;
            border-radius: 50%;
          }

          .getPhoneBtn::after {
            border: none;
          }
        }

        .img {
          width: 92rpx;
          height: 92rpx;
          margin: 0 44rpx;
        }
      }
    }
  }
}

.ipt-box {
  background: #f5f5f5;
  height: 96rpx;
  border-radius: 16rpx;
  width: calc(100% - 60rpx);
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.placeholderStyle {
  color: #cccccc;
  font-size: 28rpx;
}

// 我同意
.check-box {
  margin-left: 20rpx;
  margin-top: 36rpx;
}

// H5底部进入首页
.bottom-box {
  display: flex;
  align-items: center;
  margin-top: 50rpx;

  .bottom-text {
    font-size: 28rpx;
    color: #333333;
  }

  .high_line {
    width: 2rpx;
    height: 32rpx;
    background: #e0e0e0;
    margin: 0 32rpx;
  }
}
</style>
